/**
 *
 */
package ru.ibrae.cr.client;

import ru.ibrae.cr.domain.BaseDocument;
import ru.ibrae.cr.domain.DocumentPersonLink;
import ru.ibrae.cr.domain.DocumentPersonType;
import ru.ibrae.cr.domain.DocumentType;
import ru.ibrae.cr.domain.Organization;
import ru.ibrae.cr.domain.Person;
import ru.ibrae.cr.domain.PredefinedDocumentType;
import ru.ibrae.cr.domain.User;
import ru.ibrae.cr.remoteclient.RemoteClientInitializer;

import ru.ibrae.excelparser1.gui.Login;

import java.io.InputStream;

import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @author pvo
 *
 */
public class TestInitializer {
    //~ Methods ----------------------------------------------------------------

    @SuppressWarnings("deprecation")
    public static void start(DbType dbType)
            throws Exception {
        Properties props = new Properties();
        InputStream input = TestInitializer.class.getClassLoader().getResourceAsStream(
                "client-" + dbType.toString() + ".properties");
        props.load(input);
        input.close();
        Lookup.clientProperties = props;

        //System.setProperty("developmentMode", "true");
        Login login = new Login(null, true);
        login.setLocationRelativeTo(null);
        login.setVisible(true);

        RemoteClientInitializer.start(null, login.login, login.password);

        List<User> users = Lookup.getDataProvider().loadAll(User.class);

        /* Lookup.getDataProvider().executeSQL(
        new String[] {
        "CREATE SEQUENCE IF NOT EXISTS citizen_categ_seq START WITH 1"
        });*/
        System.out.println("Test context initialized");
    }

    public static void stop() {
        RemoteClientInitializer.stop();
    }

    /**
     * Этот метод нужен только в тестах. В реальной базе все данные уже есть.
     */
    @SuppressWarnings("deprecation")
    public static void createPredefinedDocumentTypes() {
        // создаем VirtualDocument с айдишником 0
        StringBuilder sb = new StringBuilder();
        sb.append(
                "INSERT INTO document_type (cr_id, shortname, fullname, predef_doc_type) VALUES (0, '");
        sb.append(PredefinedDocumentType.VirtualDocument.getShortName());
        sb.append("', '");
        sb.append(PredefinedDocumentType.VirtualDocument.getFullName());
        sb.append("', '");
        sb.append(PredefinedDocumentType.VirtualDocument.name());
        sb.append("')");

        try {
            Lookup.getDataProvider().executeSQL(new String[]{sb.toString()});
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        // создаем остальные типы
        for (PredefinedDocumentType pdt : PredefinedDocumentType.values()) {
            if (pdt != PredefinedDocumentType.VirtualDocument) {
                DocumentType dt = new DocumentType();
                dt.setPredefinedDocumentType(pdt);
                dt.setShortName(pdt.getShortName());
                dt.setFullName(pdt.getFullName());
                dt.setCategory(pdt.getEventCategory());
                Lookup.getDataProvider().saveObject(dt);
            }
        }

        // Использование метода loadAll может загрузить на клиент очень много данных
        // за счет коллекций.
        List<DocumentType> allTypes = Lookup.getDataProvider().loadAll(DocumentType.class);

        //Assert.assertEquals(PredefinedDocumentType.values().length,
        //                   allTypes.size());
    }

    public static Person createPerson(final String lastName,
            final String firstName,
            final String middleName) {
        Person person = new Person();
        person.setLastName(lastName);
        person.setFirstName(firstName);
        person.setMiddleName(middleName);

        return Lookup.getDataProvider().saveObject(person);
    }

    public static Organization createOrganization(final String name) {
        Organization org = new Organization();
        org.setShortname(name);
        org.setName(name);

        return Lookup.getDataProvider().saveObject(org);
    }

    public static BaseDocument createRequest(final Organization issueOrg,
            final String number,
            final DocumentType certType,
            final int certNumBegin,
            final int certNumEnd) {
        BaseDocument request = new BaseDocument();
        request.setType(PredefinedDocumentType.Request.getDocumentType());
        request.setIssueOrganization(issueOrg);
        request.setIssueDate(new Date());
        request.setNumber(number);
        request.setAddInfoDocumentType(certType);
        request.setAddInfoDocumentNumBegin(certNumEnd);
        request.setAddInfoDocumentNumEnd(certNumEnd);

        return Lookup.getDataProvider().saveObject(request);
    }

    public static BaseDocument createCertificate(final String series,
            final String number,
            final PredefinedDocumentType documentType) {
        BaseDocument document = new BaseDocument();
        document.setType(documentType.getDocumentType());
        document.setIssueDate(new Date());
        document.setSeries(series);
        document.setNumber(number);
        document.setName(document.createDocumentName());

        BaseDocument bd = Lookup.getDataProvider().saveObject(document);

        return bd;
    }

    public static DocumentPersonLink createDocumentLink(final Person person,
            final String series,
            final String number,
            final PredefinedDocumentType documentType,
            final DocumentPersonType linkType) {
        BaseDocument document = new BaseDocument();
        document.setType(documentType.getDocumentType());
        document.setIssueDate(new Date());
        document.setSeries(series);
        document.setNumber(number);
        document.setName(document.createDocumentName());

        DocumentPersonLink link = new DocumentPersonLink();
        link.setDocument(document);
        link.setPerson(person);
        link.setType(linkType);
        Lookup.getDataProvider().saveObjects(document, link);

        return link;
    }

    public static void main(String args[])
            throws Exception {
        TestInitializer.start(DbType.H2);
        Thread.sleep(1000);
        TestInitializer.stop();
    }
}
